<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="15">
          <a-descriptions-item> {{ userData.patientInfo?.bedCode || '-' }}床</a-descriptions-item>
          <a-descriptions-item> {{ userData.patientInfo?.brName || '-' }}</a-descriptions-item>
          <a-descriptions-item> {{ userData.patientInfo?.brXb || '-' }}</a-descriptions-item>
          <a-descriptions-item> {{ userData.patientInfo?.brAge || '-' }}</a-descriptions-item>
          <a-descriptions-item> {{ userData.patientInfo?.deptName || '-' }}</a-descriptions-item>
          <a-descriptions-item> {{ userData.bldComponentName || '-' }}</a-descriptions-item>
          <a-descriptions-item> {{ userData.bldTypeName || '-' }}型</a-descriptions-item>
          <a-descriptions-item> {{ userData.bldTypeRhName || '-' }}</a-descriptions-item>
          <a-descriptions-item> {{ userData.transfusionVolume || '-' }}ml</a-descriptions-item>
          <a-descriptions-item> {{ userData.transfusionName || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable :data-source="dataSource" max-fill :extra-height="64" column-code="000638" :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')">
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'localCode'">
            <EditCell title="储血号">
              <BaseInput v-model:value="record.localCode" placeholder="请输入" @keyup.enter="onScanCode(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'bldVolume'">
            <EditCell title="储血量">
              <BaseInput v-model:value="record.bldVolume" suffix="ml" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'matchName'">
            <EditCell title="配血方法">
              <SelectItem v-model:value="record.matchCode" type="DT00297" placeholder="请选择" @change="editRow(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'matchRecultName'">
            <EditCell title="配血结果">
              <a-select v-model:value="record.matchRecultCode" placeholder="请选择" @change="onSelectMatchRecult($event, record)">
                <a-select-option v-for="item in matchList" :key="item" :value="item.id">{{ item.matchResult }}</a-select-option>
              </a-select>
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'isPass'">
            <div v-if="record?.isPass === '0'">否</div>
            <div v-if="record?.isPass === '1'">是</div>
          </template>
          <template v-if="column.dataIndex === 'antibodyReport'">
            <EditCell title="抗体筛查报告">
              <a-input v-model:value="record.antibodyReport" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>

          <template v-if="column.dataIndex === 'expireDate'">
            <EditCell title="失效日期">
              <a-date-picker v-model:value="record.expireDate" value-format="YYYY-MM-DD" placeholder="请输入" @blur="editRow(record)" />
            </EditCell>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const route = useRoute()
const router = useRouter()
const userData = ref({})
const loading = ref(false)
const dataSource = ref([])
const matchList = ref([])

// 扫码
const onScanCode = async (row) => {
  const { code, data, msg } = await post('/bloodm/BldTransfusionRecord/getBldTransfusionMatchRecordInfo', {
    localCode: row.localCode,
    appLsh: route.query?.appLsh,
    bldVolume: row?.bldVolume
  })
  if (code !== 0) return message.error(msg)
  row.antibodyReport = data?.antibodyReport
  row.appLsh = data?.appLsh
  row.appLsh = data?.appLsh
  row.bldVolume = data?.bldVolume
  row.collectDate = data?.collectDate
  row.createTime = data?.createTime
  row.createUser = data?.createUser
  row.createUserName = data?.createUserName
  row.expireDate = data?.expireDate
  row.externalCode = data?.externalCode
  row.id = data?.id
  row.isPass = data?.isPass
  row.localCode = data?.localCode
  row.matchRecultCode = data?.matchRecultCode
  row.matchRecultName = data?.matchRecultName
  row.updateTime = data?.updateTime
  row.updateUser = data?.updateUser
}

// 配血结果
const onSelectMatchRecult = async (item, row) => {
  const matchItem = matchList.value.find((i) => i.id === item)
  row.isPass = matchItem?.isPass === '0' ? '否' : '是'
  editRow(row)
}

// 修改和保存
const editRow = (row) => !row.isNew && fetchSave()
const fetchSave = async () => {
  const { code, msg } = await post('/bloodm/BldTransfusionRecord/doSaveBldTransfusionMatchRecordList', {
    appLsh: route.query?.appLsh,
    bldTransfusionRecordList: dataSource.value
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.success('保存成功')
  getData()
}

//添加行
const addRow = async () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss') }
  dataSource.value.push(addRow)
}

// 获取配血明细列表
const getData = async () => {
  loading.value = true
  const { data, code, msg } = await post('/bloodm/BldTransfusionRecord/getBldTransfusionRecordList', {
    appLsh: route.query?.appLsh || '',
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  dataSource.value = data
}

// 获取配血结果列表
const getMatchList = async () => {
  const { code, data, msg } = await post('bloodm/BldTransfusionRecord/getBldTransfusionResultList', {})
  if (code !== 0) return message.error(msg)
  matchList.value = data
}

// 获取上面信息
const getMatchInfo = async () => {
  const { code, data, msg } = await post('/bloodm/BldTransfusionRecord/getBldTransfusionMatchList', { zjm: route.query?.appLsh })
  if (code !== 0) return message.error(msg)
  data.length && (userData.value = data[0])
}

const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  newRow.forEach((item) => {
    if (!item.localCode && !item.matchRecultName) {
      message.destroy()
      message.error('请填写完整信息')
      return
    } else {
      fetchSave()
    }
  })
}

watchEffect(() => {
  if (route.query?.appLsh) {
    getMatchInfo()
    getMatchList()
    getData()
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
